<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>修改页面</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../res/layuis/dist/css/layui.css"  media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
    <script src="../../res/layuis/dist/layui.all.js" charset="utf-8"></script>
    <!--<script src="../../res/layuis/dist/layui.js" charset="utf-8"></script>-->
    <!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
    <script src="../../res/js/jquery-3.1.1.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<form class="layui-form" action="" lay-filter="example" id="attachmentUpdate">
    <div class="layui-form-item layui-hide">
        <label class="layui-form-label">辅助功能类型</label>
        <input class="layui-input-block">
        <input type="text" name="attachType" id="attachType" value="10" class="layui-input" style="width: 280px">
    </div>
    <div class="layui-form-item layui-hide">
        <label class="layui-form-label">ID</label>
        <div class="layui-input-block">
            <input type="text" name="attachId" id="attachId" autocomplete="off"  class="layui-input" style="width: 280px">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">标题</label>
        <div class="layui-input-block">
            <input type="text" name="attachName" lay-verify="title" autocomplete="off" placeholder="请输入标题" class="layui-input" style="width: 280px">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">发布时间</label>
            <div class="layui-input-inline">
                <input type="text" name="attachTime" class="layui-input" lay-verify="date" id="date1" placeholder="yyyy-MM-dd">
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">有效时间</label>
            <div class="layui-input-inline">
                <input type="text" name="attachValidTime" class="layui-input" lay-verify="date" id="date2" placeholder="不填则为永久有效">
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">发布对象</label>
        <div class="layui-input-block">
            <div id="treeUsers" class="demo-tree-more"></div>
        </div>
    </div>

    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">编辑器</label>
        <div class="layui-input-block">
            <textarea class="layui-textarea" name="content" id="attachContent"></textarea>
        </div>
    </div>

    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-block">
            <textarea placeholder="请输入内容" lay-verify="content|required" class="layui-textarea" name="remark" ></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">文件上传</label>
        <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button>
        <div>
            <div style="width: 110px; float: left; border: 1px solid; visibility: hidden;"></div>
            <div class="layui-upload-list" style="width: 80%; float: left;">
                <table class="layui-table">
                    <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr></thead>
                    <tbody id="demoList"></tbody>
                </table>
                <button type="button" class="layui-btn layui-hide" id="testListAction">开始上传</button>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="button" class="layui-btn layui-btn-normal" id="LAY-component-form-getval">提交</button>
        </div>
    </div>
</form>


<script>
    var editor;
    var files;
    var fileTypeId = "";
    var fileType = "";
    var ajaxLoading = 0;
    var fileDataIds = "";
    layui.use(['form', 'layedit', 'laydate', 'upload', 'tree', 'util'], function() {
        var form = layui.form
            ,$ = layui.jquery
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate
            , upload = layui.upload
            , tree = layui.tree
            , util = layui.util;

        //多文件列表示例
        var demoListView = $('#demoList')
            ,uploadListIns = upload.render({
            elem: '#testList'
            ,url: '../../attachment/insertFileData'
            ,accept: 'file'
            ,field:'fileData'
            ,multiple: true
            ,auto: false
            ,bindAction: '#testListAction'
            ,before: function() {
                uploadListIns.config.data.fileType = fileType;
                uploadListIns.config.data.fileTypeId = fileTypeId;
            }
            ,choose: function(obj){
                files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function(index, file, result){
                    var tr = $(['<tr id="upload-'+ index +'">'
                        ,'<td>'+ file.name +'</td>'
                        ,'<td>'+ (file.size/1024).toFixed(1) +'kb</td>'
                        ,'<td>等待上传</td>'
                        ,'<td>'
                        ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        ,'</td>'
                        ,'</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function(){
                        console.log("============重选上传");
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function(){
                        var tr = demoListView.find('tr#upload-'+ index)
                            ,tds = tr.children();
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    demoListView.append(tr);
                });
            }
            ,done: function(res, index, upload){
                if(res.fileMessage.fileDataState === '1'){ //上传成功
                    var tr = demoListView.find('tr#upload-'+ index)
                        ,tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    //ds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            ,error: function(index, upload){
                var tr = demoListView.find('tr#upload-'+ index)
                    ,tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
            ,allDone: function(obj){ //当文件全部被提交后，才触发
                if (obj.aborted === 0){
                    layer.msg('修改成功', {
                        icon: 1,
                        time: 2000,
                        end: function () {
                            var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                            parent.layer.close(index);
                            parent.layui.table.reload("demo");
                        }
                    });
                }else {
                    layer.msg('文件上传失败', {
                        icon: 1,
                        time: 2000,
                        end: function () {
                            var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                            parent.layer.close(index);
                        }
                    });
                }

            }
        });

        //日期
        laydate.render({
            elem: '#date1'
            , isInitValue: true
        });
        laydate.render({
            elem: '#date2'
            , trigger: 'click'
            , isInitValue: true
        });

        //创建一个编辑器
        editor = layedit.build('attachContent');

        //表单提交
        layui.$('#LAY-component-form-getval').on('click', function () {
            var formData = new FormData(document.getElementById("attachmentUpdate"));

            var attachFile = layedit.getContent(editor);
            formData.append("attachContent", attachFile);

            var checkedData = tree.getChecked('childrenNode'); //获取选中节点的数据
            var treeUserIds = "";
            var treeUserTitles = "";
            $.each(checkedData,function(index,item){
                $.each(item.children,function(indexs,items){
                    treeUserIds += items.id + ",";
                    treeUserTitles += items.title + ",";
                });
            });
            console.log('============'+treeUserTitles);
            formData.append("treeUserIds",treeUserIds);
            formData.append("treeUserTitles",treeUserTitles);
            formData.append("fileDataIds",fileDataIds);
            var data = form.val('example');
            var attachName = data.attachName;
            if (attachName === "" || attachName === null || attachName === undefined){
                ajaxLoading = 2;
                layer.confirm('标题不能为空', function(index){
                    layer.close(index);
                });
            }else if (attachFile === "" || attachFile === null || attachFile === undefined){
                ajaxLoading = 2;
                layer.confirm('编辑器内容不能为空', function(index){
                    layer.close(index);
                });
            }else if (treeUserIds === "" || treeUserIds === null || treeUserIds === undefined){
                ajaxLoading = 2;
                layer.confirm('发布对象不能为空', function(index){
                    layer.close(index);
                });
            }else {

            }

            if (ajaxLoading === 0) {
                ajaxLoading = 1;
                $.ajax({
                    url: '../../attachment/updateByPrimaryKeySelective', //数据接口
                    data: formData,
                    type: "POST",
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    success: function (data) {

                        if(data.fileMessage.attachState === '1'){
                            //var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                            //parent.layer.close(index);

                            fileTypeId = data.fileMessage.attachId;
                            fileType = data.fileMessage.attachType;

                            if (jQuery.isEmptyObject(files)){
                                var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                                parent.layer.close(index);
                                parent.layui.table.reload("demo");
                            }else {
                                $("#testListAction").click();
                            }     //为空返回true             用于对象未指定类型，或指定类型为数组，对象三者时可用，其他类型不可用

                        } else {
                            layer.confirm('修改失败', function(){

                            });

                        }


                    }
                });
            }else if (ajaxLoading === 1 || ajaxLoading === 3){
                layer.msg('玩命加载中',{
                    icon: 1,
                    time: 2000,
                    end: function () {

                    }
                });
            }else if (ajaxLoading === 1){
                layer.msg('玩命更新中',{
                    icon: 1,
                    time: 2000,
                    end: function () {

                    }
                });
            }else if (ajaxLoading === 2){
                ajaxLoading = 0;
            }



        });

    });
    //起始赋值事件
    function begins() {
        var form = layui.form
            ,$ = layui.jquery
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate
            , tree = layui.tree
            , util = layui.util;
        var url = "../../attachment/selectByPrimaryKey";
        var attachId = $("#attachId").val();

        var data = {
            attachId: attachId
        };
        $.post(url, data, function (obj) {
            form.val('example', {
                "attachId": obj.data.attachId//文件id
                ,"attachType": obj.data.attachType//文件类型
                ,"attachName": obj.data.attachName // "name": "value"
                , "attachTime": obj.data.attachTime
                , "attachValidTime": obj.data.attachValidTime
                , "remark": obj.data.remark  //备注
            });

            var fileHtml = "";
            var demoListView = $('#demoList');
            if (obj.fileMessage != null){
                $.each(obj.fileMessage,function (index,dom) {
                    fileHtml = $(['<tr id="upload-'+ index +'">'
                        ,'<td title="'+ dom.fileId +'">'+ dom.fileName +'</td>'
                        ,'<td>'+ dom.fileSize+'</td>'
                        ,'<td>'
                        ,'<a href="../../'+dom.fileSite+'" download>文件下载</a>'
                        ,'</td>'
                        ,'<td>'
                        ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        ,'<a class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteFileTr('+ index +')">删除</a>'
                        ,'</td>'
                        ,'</tr>'].join(''));
                    demoListView.append(fileHtml);
                });

            }


            tree.render({
                elem: '#treeUsers' //默认是点击节点可进行收缩
                ,data: obj.treeUsers
                ,id: 'childrenNode'
                ,showCheckbox : true //是否显示复选框

            });

            var checkedUsers = obj.checkedUser;
            tree.setChecked('childrenNode', checkedUsers); //勾选指定节点[4,5,6,12]12

            $("#attachContent").text(obj.data.attachContent);
            editor = layedit.build('attachContent',{hideTool: [
                    'image' //插入图片
                    ,'help' //帮助
                ]}); //建立文档编辑器
        });
    }

    //动态删除点击事件
    function deleteFileTr(index) {
        var form = layui.form
            ,$ = layui.jquery
            , layer = layui.layer;
        //var tr = $(this).parents("#upload-"+index);
        var demoListView = $('#demoList');
        var tr = demoListView.find('tr#upload-'+ index)
            ,tds = tr.children();
        var fileId = tds.eq(0).attr("title");
        var fileName = tds.eq(0).text();
        layer.confirm('确定删除选中的'+fileName+'文件吗？', function(index){
            fileDataIds += fileId + ',';
            tr.remove();
            layer.close(index);
        });


       /* $.ajax({
            type: 'post',
            url: '../../attachment/deleteFileData', //数据接口
            data: {
                'fileId':fileId
            },
            dataType: 'json',
            success: function (data) {
                if(data.fileMessage.fileDataState === '1'){
                    layer.msg('删除成功',{
                        icon: 1,
                        time: 1000,
                        end: function () {
                            tr.remove();
                            //table.reload('demo',{});
                            //window.location.reload();
                        }
                    });
                }else{
                    layer.msg('删除失败',{
                        icon: 1,
                        time: 1000,
                        end: function () {
                            //table.reload('demo',{});
                            //window.location.reload();
                        }
                    });
                }

            }
        });*/


    }
</script>
</body>
</html>